// @login $ register
const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const keys = require("../../config/keys");
const passport = require("passport");
const moment = require("moment");

const User = require("../../models/User");

// Get test 测试接口
router.get("/test", (req, res) => {
  res.json("测试接口");
});

// post Register 注册接口
router.post("/register", (req, res) => {
  // res.json(req.body);
  // 查询数据库中是否有此人学号
  User.findOne({ card: req.body.card }).then((user) => {
    if (user) {
      // 学号存在
      return res.status(400).json("学号已存在");
    } else {
      const newUser = new User({
        name: req.body.name,
        password: req.body.password,
        card: req.body.card,
        phone: req.body.phone,
        status: req.body.status,
        identity: req.body.identity,
        createdAt: moment(req.body.createdAt).format("YYYY-MM-DD"),
        editor: req.body.editor,
      });

      bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(req.body.password, salt, (err, hash) => {
          if (err) throw err;

          newUser.password = hash;

          newUser.save().then((user) => res.json(user));
        });
      });
    }
  });
});

// post Login 登录接口
router.post("/login", (req, res) => {
  const card = req.body.card;
  const password = req.body.password;

  // 查询数据库
  User.findOne({ card }).then((user) => {
    if (!user) {
      return res.status(400).json("学号不存在");
    }

    if (user.editor !== "能") {
      return res.status(400).json("您没有登录权限");
    }

    // 密码匹配
    bcrypt.compare(password, user.password).then((isMatch) => {
      if (isMatch) {
        const rule = { id: user.id, name: user.name };

        // jwt.sign('规则','加密名字','过期时间','箭头函数')
        jwt.sign(rule, keys.secretOrKey, { expiresIn: 3600 }, (err, token) => {
          if (err) throw err;
          res.json({
            success: true,
            token: "Bearer " + token,
          });
        });
        // res.json("success");
      } else {
        return res.status(400).json("密码错误");
      }
    });
  });
});

// Get current 获取单个人员信息
router.get(
  "/current",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    // res.json("success");
    // res.json(req.user);
    res.json({
      id: req.user.id,
      name: req.user.name,
      card: req.user.card,
      status: req.user.status,
      identity: req.user.identity,
      editor: req.user.editor,
    });
  }
);
// Get allcurrent 获取所有人员信息
router.get(
  "/allcurrent",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    // res.json("success");
    // res.json(req.user);
    User.find().then((users) => res.json(users));
  }
);

// Delete delete 删除人员信息
router.delete(
  "/delete/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    User.findByIdAndRemove(req.params.id)
      .then((user) => {
        res.json(user);
      })
      .catch((err) => {
        res.status(404).json("删除人员失败！");
      });
  }
);

// Post add 后台添加人员接口
router.post(
  "/add",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    User.findOne({ card: req.body.card }).then((user) => {
      if (user) {
        // 学号存在
        return res.status(400).json("学号已存在");
      } else {
        const newUser = new User({
          name: req.body.name,
          password: req.body.password || "123456",
          card: req.body.card,
          phone: req.body.phone,
          status: req.body.status,
          identity: req.body.identity,
          createdAt: req.body.createdAt,
          editor: req.body.editor,
        });

        bcrypt.genSalt(10, function (err, salt) {
          bcrypt.hash(req.body.password || "123456", salt, (err, hash) => {
            if (err) throw err;

            newUser.password = hash;

            newUser.save().then((user) => res.json(user));
          });
        });
      }
    });
  }
);

// Post edit 后台编辑人员接口
router.post(
  "/edit/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const userFields = {};
    if (req.body.name) userFields.name = req.body.name;
    if (req.body.card) userFields.card = req.body.card;
    if (req.body.phone) userFields.phone = req.body.phone;
    if (req.body.status) userFields.status = req.body.status;
    if (req.body.identity) userFields.identity = req.body.identity;
    if (req.body.createdAt) userFields.createdAt = req.body.createdAt;
    if (req.body.editor) userFields.editor = req.body.editor;

    User.findOneAndUpdate(
      { _id: req.params.id }, // 查询这个项目id
      { $set: userFields }, // 设置内容
      { new: true } // 新东西
    ).then((user) => res.json(user));
  }
);

module.exports = router;
